package com.example.btchat.server;

import java.io.IOException;

import android.widget.Toast;

import com.example.btchat.Message;

public class ReaderThread extends Thread
{
	private MainActivity parent;
	
	public ReaderThread(MainActivity parent)
	{
		this.parent = parent;
	}
	
	@Override
	public void run()
	{
		String message;
		
		while(true)
		{
			ReaderThread.interrupted(); // clear interrupted flag
			
			if(parent.connections.size() == 0)
			{
				try
				{
					Thread.sleep(10000); // main thread will wake us when a client
																// connects
				}
				catch(InterruptedException e)
				{}
			}
			
			for(Connection connection : parent.connections)
			{
				message = "";
				try
				{
					while(connection.input.available() > 0)
					{
						byte[] buffer = new byte[500];
						connection.input.read(buffer);
						try
						{
							Thread.sleep(10);
						}
						catch(InterruptedException e)
						{}
						message += buffer;
					}
				}
				catch(IOException e)
				{
					Toast.makeText(parent, parent.getString(
						R.string.msg_lost_connection,
						connection.socket.getRemoteDevice().getName()
						), Toast.LENGTH_SHORT).show();
					connection.close();
					parent.connections.remove(connection);
				}
				if(message != "")
					sendMessage(connection, message);
			}
			
			// process at most one message per second
			try
			{
				Thread.sleep(1000);
			}
			catch(InterruptedException e)
			{}
		}
	}
	
	private void sendMessage(Connection aConnection, String message)
	{
		final Message msg = new Message(aConnection.socket.getRemoteDevice().getName(), message);
		
		parent.runOnUiThread(new Runnable()
		{
			@Override
			public void run()
			{
				parent.onMessageSent(msg);
			}
		});
	}
}
